//
//  XHLeftViewController.m
//  xinhua_sx
//
//  Created by 党阳阳 on 14-5-23.
//  Copyright (c) 2014年 broadwave.com. All rights reserved.
//

#define LIST @[@"首页",@"我的收藏",@"投票",@"版本更新",@"设置",@"关于",@"意见反馈"]
#define IMG @[@"leftmenu_home.png",@"leftmenu_myattention.png",@"leftmenu_vote1.png",@"leftmenu_update.png",@"leftmenu_setting.png",@"leftmenu_about.png",@"leftmenu_about.png"]
#import "XHLeftViewController.h"

#import "XHHomeViewController.h"
#import "XHMainViewController.h"
#import "XHCollectionViewController.h"
#import "ReactiveCocoa.h"
#import "XHVoteViewController.h"
#import "XHUpdateViewController.h"
#import "XHSettingViewController.h"
#import "XHAboutViewController.h"
#import "XHFeedbackViewController.h"
#import "XHMessagelogViewController.h"
#import "XHLoginViewController.h"
#import "dangeViewController.h"
#import "gerenViewController.h"
#import "MBProgressHUD.h"

@interface leftUitableViewCell : UITableViewCell
@end

@implementation leftUitableViewCell

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, 2, 240, 38)];
        view.backgroundColor = [UIColor whiteColor];
        view.alpha = 0.1;
        [self addSubview:view];
    }
    return self;
}
- (void) layoutSubviews
{

    [super layoutSubviews];
    self.frame = CGRectMake(5, self.frame.origin.y,240 , self.frame.size.height);
    self.imageView.frame = CGRectMake(10, 10, 20, 20 );
    self.textLabel.frame = CGRectMake(40, 0, self.frame.size.width-50, self.frame.size.height);
  
}

@end

@interface XHLeftViewController ()
{
    MBProgressHUD* HUD;
}

@end

@implementation XHLeftViewController
@synthesize webView = _webView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        NSArray *array = [[NSBundle mainBundle]loadNibNamed:@"LeftView" owner:self options:nil];
        UIView *view = [array objectAtIndex:0];
        CGRect rect = self.view.frame;
        CGFloat oY = kIOS_VERSION<7.0?0:20;
        [view setFrame:CGRectMake(0, oY, rect.size.width, rect.size.height-oY)];
        [self.view addSubview:view];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
   
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    
    
    _lable.text = @"点击登录";
    if ([defaults objectForKey:@"UID"])_lable.text = @"欢迎您";
    _lable.textColor = [UIColor whiteColor];
    
    UITapGestureRecognizer *tap;
    tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapLoginButton:)];
    [_person addGestureRecognizer:tap];
    _person.userInteractionEnabled  = YES;
    tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapLoginButton:)];
    _lable.userInteractionEnabled = YES;
    [_lable addGestureRecognizer:tap];
    
   
    // Do any additional setup after loading the view from its nib.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginNotification) name:@"Login" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logoutNotification) name:@"Logout" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logoutNotification1) name:@"Logout1" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logoutNotification2) name:@"Logout2" object:nil];
    UIWebView* webView = [[UIWebView alloc] init];//版本更新
    webView.delegate = self;
    self.webView = webView;
   
    
}

- (void)loginNotification
{
    _lable.text = @"欢迎您";
    [self.view setNeedsDisplay];
    gerenViewController* v1 = [[gerenViewController alloc] init];
    [_delegate changeContentViewWithViewController:v1];
    
}
- (void)logoutNotification1
{
     NSLog(@"33333");
     _lable.text = @"点击登录";
    //[self.view setNeedsDisplay];
    XHLoginViewController *loginViewController = [[XHLoginViewController alloc] init];
    //lf presentViewController:loginViewController animated:YES completion:nil];
    [_delegate changeContentViewWithViewController:loginViewController];
    UIAlertView* v1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"修改成功,请重新登录!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [v1 show];
}
- (void)logoutNotification2
{
    XHLoginViewController *loginViewController = [[XHLoginViewController alloc] init];
    //lf presentViewController:loginViewController animated:YES completion:nil];
    [_delegate changeContentViewWithViewController:loginViewController];
}

- (void)logoutNotification
{
    _lable.text = @"点击登录";
    [self.view setNeedsDisplay];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [LIST count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"cell";
    leftUitableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[leftUitableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        cell.backgroundColor = [UIColor clearColor];
    }
    
    cell.imageView.image = [UIImage imageNamed:[IMG objectAtIndex:indexPath.row]];
    //cell.backgroundColor = [UIColor colorWithRed:74.0/255 green:149.0/255 blue:191.0/255 alpha:0.5];
    cell.textLabel.text = [LIST objectAtIndex:indexPath.row];
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    
    return cell;
}


#pragma mark - Table view delegate

-(void)webLoad
{
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.labelText = @"正在检查更新";
    HUD.dimBackground = YES;
    [self.view addSubview:HUD];
    [HUD show:YES];
    NSString* https = [NSString stringWithFormat:@"http://183.203.18.45:7001/jeesite/version/%@.plist",URLEND];
    id json = [NSDictionary dictionaryWithContentsOfURL:[NSURL URLWithString:https]];
    [HUD hide:YES];
    if (json != nil)
    {
        
        NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
        NSString *currentVersion = [infoDic objectForKey:@"CFBundleVersion"];
        
        NSLog(@"cur = %@",currentVersion);
        if (![json[@"items"][0][@"metadata"][@"bundle-version"] isEqualToString:currentVersion] && [json[@"items"][0][@"metadata"][@"bundle-version"] length]>0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"有新的版本更新，是否前往更新？" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"更新", nil];
            alert.tag = 90002;
            [alert show];
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"此版本为最新版本" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            alert.tag = 90001;
            [alert show];
        }
        
        NSLog(@"json = %@",json[@"items"][0][@"metadata"][@"bundle-version"]);
    }
    else
    {
        
        NSLog(@"error");
    }


}

//版本更新
-(void)webViewDidStartLoad:(UIWebView *)webView
{
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.labelText = @"正在检查更新";
    HUD.dimBackground = YES;
    [self.view addSubview:HUD];
    [HUD show:YES];
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [HUD hide:YES];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"网络连接失败!请稍后重试!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    [HUD hide:YES];
    NSString *js = @"document.getElementById('version').innerHTML";
    NSString *pageSource = [webView stringByEvaluatingJavaScriptFromString:js];
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion = [infoDic objectForKey:@"CFBundleVersion"];
    
    
    if (![pageSource isEqualToString:currentVersion] && [pageSource length]> 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"有新的版本更新，是否前往更新？" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"更新", nil];
        alert.tag = 90002;
        [alert show];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"此版本为最新版本" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 90001;
        [alert show];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 90002)
    {
        if (buttonIndex==1) {
            //
            //[[UIApplication sharedApplication]openURL:url];
                        NSString *u=[NSString stringWithFormat:@"http://www.xhsx.org:7001/jeesite/version/%@.html",URLEND];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:u]]; //复制时替换成  发布的地址
        }
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    XHBasicViewController *viewController;
    if (indexPath.row == 3)
    {
        [self webLoad];
        return;
    }
    switch (indexPath.row) {
        case 0:
            viewController = [[XHHomeViewController alloc] init];
            break;
        case 1:
            viewController = [[XHCollectionViewController alloc] init];
            break;
        //case 2:
          //  viewController = [[XHMessagelogViewController alloc]init];
          //  break;
        case 2:
            viewController = [[XHVoteViewController alloc] init];
            break;
        case 3:
            //版本更新
            
            
            return;
            break;
        case 4:
            viewController = [[XHSettingViewController alloc] init];
            break;
        case 5:
            viewController = [[XHAboutViewController alloc] init];
            break;
        case 6:
            viewController = [[XHFeedbackViewController alloc] init];
            break;
        default:
            
            break;
    }
    NSAssert(viewController, @"未曾初始化viewcontroller in XHLeftViewController");
    if ([_delegate respondsToSelector:@selector(showLeftView)]) {
        
        
        [_delegate changeContentViewWithViewController:viewController];
    }
    
    
}

#pragma mark loginButton

- (void)tapLoginButton:(id)sender
{
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    
    
    
    if ([defaults objectForKey:@"UID"]) {
        gerenViewController* ve = [[gerenViewController alloc] init];
        //UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定注销？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"注销", nil];
        //alertView.delegate =self;
        //[alertView show];
         [_delegate changeContentViewWithViewController:ve];
       
        
    }else{
    
        XHLoginViewController *loginViewController = [[XHLoginViewController alloc] init];
        //lf presentViewController:loginViewController animated:YES completion:nil];
        [_delegate changeContentViewWithViewController:loginViewController];
    }
    
}
/*
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        
            
            break;
        case 1:{
            NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
            
            [defaults setObject:nil forKey:@"UID"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"Logout" object:nil];
            
            break;
        }
        default:
            break;
    }
}*/
@end
